﻿using Newtonsoft.Json;

namespace Micro.Extensions.Utilities
{
    public static class JsonSerializerExtension
    {
        private static readonly JsonSerializerSettings Settings;

        static JsonSerializerExtension()
        {
            Settings = new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Error,
            };
        }

        /// <summary>
        /// 序列化为Json字符串
        /// </summary>
        public static string ToJson(this object item, JsonSerializerSettings settings = null)
        {
            return JsonConvert.SerializeObject(item, settings ?? Settings);
        }

        /// <summary>
        /// 序列化为缩进Json字符串
        /// </summary>
        public static string ToIndentedJson(this object item, JsonSerializerSettings settings = null)
        {

            return JsonConvert.SerializeObject(item, Formatting.Indented, settings ?? Settings);
        }

        /// <summary>
        /// Json字符串反序列化对象
        /// </summary>
        public static T FromJsonToObj<T>(this string jsonString, JsonSerializerSettings settings = null)
        {
            return JsonConvert.DeserializeObject<T>(jsonString, settings ?? Settings);
        }


    }
}
